﻿using ciji.Application.Dto;
using ciji.Core;
using Furion.DatabaseAccessor;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace ciji.Application.Data
{
    /// <summary>
    /// 日间评定
    /// </summary>
    [ApiDescriptionSettings("日间评定", Order = 700, Description = "日间评定")]
    [LoggingMonitor]
    public class RijianService : IDynamicApiController
    {

        private SqlSugarRepository<cts_RijianAssessType> _assessTypeRep;
        private SqlSugarRepository<cts_RijianGroup> _groupRep;
        private SqlSugarRepository<cts_AssessRijian> _orgRep;
        private SqlSugarRepository<cts_RijianAssessInfo> _assessInfoRep;          
        private SqlSugarRepository<cts_RijianImg> _rijianImgRep;
        private SqlSugarRepository<cts_RijianAssessImg> _rijianAssessImgRep;  



        private SqlSugarRepository<cts_Employee> _employeeRep;




        public RijianService(SqlSugarRepository<cts_RijianAssessType> assessTypeRep
            , SqlSugarRepository<cts_RijianGroup> groupRep
            , SqlSugarRepository<cts_AssessRijian> orgRep
            , SqlSugarRepository<cts_RijianAssessInfo> assessInfoRep 
            , SqlSugarRepository<cts_RijianImg> rijianImgRep
            , SqlSugarRepository<cts_RijianAssessImg> rijianAssessImgRep 

            , SqlSugarRepository<cts_Employee> employeeRep)
        {
            _assessTypeRep = assessTypeRep;
            _groupRep = groupRep;
            _orgRep = orgRep;
            _assessInfoRep = assessInfoRep;

            _rijianImgRep = rijianImgRep;
            _rijianAssessImgRep = rijianAssessImgRep;  

            _employeeRep = employeeRep;
        }
        /// <summary>
        /// 查询评定项目
        /// </summary>     
        /// <returns></returns>
        [HttpGet]
        public List<cts_RijianAssessType> GetRijianAssessType()
        {

            return _assessTypeRep.AsQueryable().OrderBy(m => m.AssessLevel).OrderBy(m => m.OrderIndex).ToList();
        }


        /// <summary>
        ///  删除评定项目
        /// </summary>
        /// <param name="gid"></param>

        public void DeleteRijianAssessType(string gid)
        {

            _assessTypeRep.AsUpdateable().SetColumns(m => m.sys_IsDelete == 1).Where(m => m.Gid == gid).ExecuteCommand();

        }
        /// <summary>
        /// 保存评定项目
        /// </summary> 
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public void SaveRijianAssessType(cts_RijianAssessType input)
        {

            if (input.Id > 0)
            {
                _assessTypeRep.Update(input);

            }
            else
            {
                input.Gid = Guid.NewGuid().ToString();
                _assessTypeRep.Insert(input);
            }
        }

        /// <summary>
        /// 导入评定项目
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public void ImportRijianAssessType(List<ImportXFYAssessType> list)
        {
            List<cts_RijianAssessType> listInfo = new List<cts_RijianAssessType>();
            var index = 0;
            foreach (var item in list)
            {
                index += 1;
                cts_RijianAssessType oa = new cts_RijianAssessType
                {
                    Gid = Guid.NewGuid().ToString(),
                    Name = item.评定项目,
                    ParentType = item.一级分类,
                    ParentType2 = item.二级分类,
                    NoStr = item.序号,
                    OrderIndex = index,
                    IsTitle = item.是否为标题,
                    sys_IsDelete = 0,
                    AssessLevel = item.星级
                };
                listInfo.Add(oa);
            }
            _assessTypeRep.Delete(m=> m.AssessLevel == list[0].星级);
            _assessTypeRep.InsertRange(listInfo);
        }

        /// <summary>
        /// 新建一个日间照料中心评定空项目
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public void SaveRijianGroup(cts_RijianGroup pGroup)
        {
            pGroup.Gid = Guid.NewGuid().ToString();
            _groupRep.Insert(pGroup);
        }
        /// <summary>
        /// 导入日间照料中心
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        [UnitOfWork]
        public void ImportAssessRijian(ImportRijian importProp)
        {
            var cEmp = _employeeRep.GetFirst(m => m.Gid == UserHelper.GetUserId());
            var pGroup = importProp.pGroup;
            List<ImportRijianDesc> listError = new List<ImportRijianDesc>();
            List<cts_AssessRijian> listinfo = new List<cts_AssessRijian>();
            var orderindex = 0; 
            var orderindexSave = _orgRep.AsQueryable().Where(m => m.GroupId == pGroup.Gid).Max(m => m.OrderIndex);
            foreach (var item in importProp.orgList)
            {
                orderindex += 1;
                orderindexSave += 1;
                cts_AssessRijian cp = new cts_AssessRijian();
                if (string.IsNullOrEmpty(item.名称))
                {
                    item.错误信息 = orderindex + ".信息不全：名称不能为空";
                    listError.Add(item);
                    continue;
                }
                cp.sys_CreateDate = DateTime.Now;
                cp.sys_Creater = cEmp.Gid;
                cp.sys_CreaterName = cEmp.EmployeeName;
                cp.Gid = Guid.NewGuid().ToString();
                cp.sys_IsDelete = 0;
                cp.Name = item.名称;
                cp.LinkName = item.联系人;
                cp.LinkPhone = item.联系方式;
                cp.Address = item.地址;
                cp.State = 0;
                cp.AssessLevel = item.申请星级;
                cp.GroupId = pGroup.Gid;
                cp.OrderIndex = orderindexSave;
                listinfo.Add(cp);
            }
            if (listError.Count > 0)
            {
                throw Oops.Bah("操作失败").WithData(listError);
            }
             
            if (string.IsNullOrEmpty(pGroup.Gid))
            {
                pGroup.Gid = Guid.NewGuid().ToString();
                pGroup.sys_CreateDate = DateTime.Now;
                pGroup.sys_Creater = cEmp.Gid;
                pGroup.sys_CreaterName = cEmp.EmployeeName;
                _groupRep.Insert(pGroup);

            }
            _orgRep.InsertRange(listinfo);
        }
        /// <summary>
        /// 查询日间照料中心项目
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public SqlSugarPagedXList<cts_RijianGroup> SearchRijianGrouphasPage(SearchPersonGrouphasPageDto input)
        {
            // 构建子查询（B表）
            var subQuery = _orgRep.AsQueryable()
                .GroupBy(a => a.GroupId)
                .Select(a => new
                {
                    GroupId = a.GroupId,
                    OrgCount = SqlFunc.AggregateCount(0), // COUNT(0)
                    AssessCount = SqlFunc.AggregateSum(SqlFunc.IIF(a.State >0, 1, 0)) // SUM(CASE WHEN State=2 THEN 1 ELSE 0 END)
                });

            // 主查询（A表左连接B表）
            return _groupRep.AsQueryable()
                 .LeftJoin(subQuery, (a, b) => a.Gid == b.GroupId)
                 .Where(a => a.IsSaved == input.issaved)
                 .WhereIF(!string.IsNullOrEmpty(input.str), a => a.GroupName.Contains(input.str))
                 .WhereIF(!string.IsNullOrEmpty(input.year), a => a.GroupYear.Equals(input.year))
                 .WhereIF(!string.IsNullOrEmpty(input.area), a => a.GroupArea.Equals(input.area))
                 .OrderByDescending(a => a.Id)
                 .Select((a, b) => new cts_RijianGroup
                 {
                     Id = a.Id.SelectAll(),
                     OrgCount = b.OrgCount,
                     AssessCount = b.AssessCount,

                 }).ToPagedList(input.page, input.size);

        }

        /// <summary>
        /// 查询日间照料中心
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public SqlSugarPagedXList<cts_AssessRijian> SearchAssessRijian(SearchOrgDto input)
        {


            return _orgRep.AsQueryable()
                 .Where(m => m.GroupId == input.groupid)
                 .WhereIF(input.state > -1, m => m.State == input.state)
                 .WhereIF(!string.IsNullOrEmpty(input.str), m => m.Name.Contains(input.str))
                 .OrderByDescending(m => m.Id).ToPagedList(input.page, input.size);

        } 
        /// <summary>
        /// 开始评定
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public cts_AssessRijian BeginRijianAssess(string gid)
        {
            var model = _orgRep.AsQueryable().Where(m => m.Gid == gid).First();
            if (model == null)
            {
                throw Oops.Bah("未找到该机构信息");
            }
           

            var listinfo =_assessInfoRep.AsQueryable().Where(m =>  m.OrgId == gid).OrderBy(m => m.ItemOrderIndex).ToList();

            if (listinfo != null && listinfo.Count > 0)
            {
                model.info = listinfo;
                return model;
            }
            else
            {

                var list = _assessTypeRep.AsQueryable().Where(m=> m.AssessLevel == model.AssessLevel).OrderBy(m => m.OrderIndex).ToList();
                var infoList = new List<cts_RijianAssessInfo>();
                var savedSql = Guid.NewGuid().ToString();
                foreach (var item in list)
                {
                    var info = new cts_RijianAssessInfo
                    { 
                        sys_CreateDate = DateTime.Now,
                        Gid = Guid.NewGuid().ToString(),
                        sys_IsDelete = 0,
                        OrgId = model.Gid,
                        OrgName = model.Name,
                        SavedSql = savedSql,
                        ItemId = item.Gid,
                        ItemName = item.Name,
                        ItemNoStr = item.NoStr,
                        IsTitle = item.IsTitle,
                        ItemOrderIndex = item.OrderIndex,
                        ItemParentType = item.ParentType,
                        ItemParentType2 = item.ParentType2,
                        ItemParentType3 = item.ParentType3,
                        IsStandard = 1,
                    };
                    infoList.Add(info);
                }
                _assessInfoRep.InsertRange(infoList);
                model.info = infoList; 
                return model;

            }
        }
        /// <summary>
        /// 获取评定详情
        /// </summary>     
        /// <returns></returns>
        [HttpGet]
        public cts_AssessRijian GetRijianAssessInfo(string gid)
        { 

            var model = _orgRep.AsQueryable().Where(m => m.Gid == gid).First();
            if (model == null)
            {
                throw Oops.Bah("未找到该机构信息");
            }
            var listinfo = _assessInfoRep.AsQueryable().Where(m => m.OrgId == gid).OrderBy(m => m.ItemOrderIndex).ToList();
            model.info = listinfo.FindAll(m => m.IsTitle == 0);
            return model;
        }

        /// <summary>
        /// 获取评定详情-包含图片
        /// </summary>     
        /// <returns></returns>
        [HttpGet]
        public cts_AssessRijian GetRijianAssessInfoHasImg(string gid)
        {
            var model = _orgRep.AsQueryable().Where(m => m.Gid == gid).First();
            if (model == null)
            {
                throw Oops.Bah("未找到该机构信息");
            }
            model.imgs=_rijianImgRep.GetList(m=>m.OrgId == gid);

            // 查询评估信息及关联图片
            var assessInfoList = _assessInfoRep.AsQueryable()
                .LeftJoin<cts_RijianAssessImg>((a, b) => a.Gid == b.OrgItemId)
                .Where(a => a.OrgId == gid)
                .OrderBy(a => a.ItemOrderIndex)
                .Select((a, b) => new cts_RijianAssessInfo
                {
                    Id = a.Id.SelectAll(),
                    Imgs = b == null ? new List<string>(): new List<string> { b.ImgUrl }

                })
                .ToList();

            return model;
        }

        /// <summary>
        /// 保存机构评定
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public void SaveRijianAssessInfo(cts_AssessRijian info)
        {
            var cEmp=_employeeRep.GetFirst(m=>m.Gid==UserHelper.GetUserId());
            var model = _orgRep.AsQueryable().Where(m => m.Gid == info.Gid).First();
            if (model == null)
            {
                throw Oops.Bah("未找到该机构信息");
            }
            if (model.State == 0)
            {
                model.CheckPerson = cEmp.Gid;
                model.CheckPersonName = cEmp.EmployeeName;
                model.CheckTime = DateTime.Now;
            }
            else
            {
                model.sys_Modifier = cEmp.Gid;
                model.sys_ModifierName = cEmp.EmployeeName;
                model.sys_ModifyDate = DateTime.Now;
            }
            model.State = 1;

            var infolist = _assessInfoRep.GetList(m=>m.OrgId==info.Gid);
            foreach (var item in infolist)
            {
                if (item.IsTitle == 0 && item.IsStandard != 1)
                {
                    model.State = 2;
                    break;
                }
            }
            _orgRep.Update(model);
        }
        /// <summary>
        /// 保存单个日间评定项目
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public cts_RijianAssessInfo SaveRijianAssessItem(cts_RijianAssessInfo item)
        {
            var cEmp = _employeeRep.GetFirst(m => m.Gid == UserHelper.GetUserId());

            if (cEmp.Auth != (cEmp.Auth | 1))
            {
                throw Oops.Bah("无权限");
            }
           
            if (item.SaveCount == 0)
            {
                item.sys_Creater = cEmp.Gid;
                item.sys_CreaterName = cEmp.EmployeeName;
                item.sys_CreateDate = DateTime.Now;
            }
            else
            {
                item.sys_Modifier = cEmp.Gid;
                item.sys_ModifierName = cEmp.EmployeeName;
                item.sys_ModifyDate = DateTime.Now;
            }
            item.SaveCount += 1; 
            _assessInfoRep.Update(item);
            return item;
        }

        /// <summary>
        /// 查询乡镇
        /// </summary>     
        /// <returns></returns>
        [HttpGet]
        public List<string> GetRijianTown(string groupid)
        {
            return _orgRep.AsQueryable().Where(m => m.GroupId == groupid && !string.IsNullOrEmpty(m.Town)).Select(m => m.Town).Distinct().ToList();

        }
        /// <summary>
        /// 转移项目
        /// </summary>     
        /// <returns></returns>
        public void TransRijianGroup(TransOrgInput input)
        {
            _orgRep.AsUpdateable().SetColumns(m => new cts_AssessRijian { GroupId = input.groupid, Town = input.town }).Where(m => m.Gid == input.gid).ExecuteCommand();
        }
         
        /// <summary>
        /// 存档
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public void SavedRijianGroup(string gid)
        {
            _groupRep.AsUpdateable().SetColumns(m => m.IsSaved == 1).Where(m => m.Gid == gid).ExecuteCommand();
        }
        /// <summary>
        /// 删除日间照料中心项目
        /// </summary>     
        /// <returns></returns>
        
        public void DeleteRijianGroup(string gid)
        {
            _groupRep.AsUpdateable().SetColumns(m => m.sys_IsDelete == 1).Where(m => m.Gid == gid).ExecuteCommand();
        }
        /// <summary>
        /// 删除日间照料中心
        /// </summary>     
        /// <returns></returns>
        
        public void  DeleteAssessRijian(string gid)
        {
            _orgRep.AsUpdateable().SetColumns(m => m.sys_IsDelete == 1).Where(m => m.Gid == gid).ExecuteCommand();
        }

        /// <summary>
        /// 获取日间照料中心信息
        /// </summary>     
        /// <returns></returns>
        [HttpGet]
        public cts_AssessRijian GetAssessRijianInfoById(string gid)
        {
            var model = _orgRep.AsQueryable().Where(m => m.Gid == gid).First();
            if (model == null)
            {
                throw Oops.Bah("未找到该机构信息");
            }
            model.imgs = _rijianImgRep.GetList(m => m.OrgId == gid);
            return model;

        }
        /// <summary>
        /// 保存日间照料中心
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public string SaveAssessRijian(cts_AssessRijian info)
        {
            // 新增操作
            if (string.IsNullOrEmpty(info.Gid))
            {
                // 获取最大排序号
                var orderIndex = _orgRep.AsQueryable()
                    .Where(m => m.GroupId == info.GroupId)
                    .Max(m => m.OrderIndex);

                // 设置新增实体属性
                info.Gid = Guid.NewGuid().ToString();
                info.OrderIndex = orderIndex + 1;

                // 插入主表
                _orgRep.Insert(info);

                // 处理图片
                if (info.imgs != null && info.imgs.Any())
                {
                    foreach (var img in info.imgs)
                    {
                        img.Gid = Guid.NewGuid().ToString();
                        img.OrgId = info.Gid;
                    }
                    _rijianImgRep.InsertRange(info.imgs);
                }

            }
            // 编辑操作
            else
            {
                _orgRep.AsUpdateable(info).IgnoreColumns(m => m.OrderIndex)
                    .Where(m => m.Gid == info.Gid)
                    .ExecuteCommand();

                // 删除旧图片
                _rijianImgRep.Delete(m => m.OrgId == info.Gid);

                // 插入新图片
                if (info.imgs != null && info.imgs.Any())
                {
                    foreach (var img in info.imgs)
                    {
                        img.Gid = Guid.NewGuid().ToString();
                        img.OrgId = info.Gid;

                    }
                    _rijianImgRep.InsertRange(info.imgs);
                }

            }
            return info.Gid;
        }
        
       
        /// <summary>
        /// 删除图片
        /// </summary>     
        /// <returns></returns>
        
        public void DeleteRijianItemImg(string gid)
        {
            _rijianAssessImgRep.AsUpdateable().SetColumns(m => m.sys_IsDelete == 1).Where(m => m.Gid == gid).ExecuteCommand();
        }
        /// <summary>
        /// 获取图片
        /// </summary>     
        /// <returns></returns>
        [HttpGet]
        public List<cts_RijianAssessImg> GetRijianItemImg(string gid)
        {
            return _rijianAssessImgRep.GetList(m => m.OrgItemId == gid);
        }

        /// <summary>
        /// 获取评定报告年份地区
        /// </summary>     
        /// <returns></returns>
        [HttpGet] 
        public List<MenuModel> GetAreaYear()
        {
            var sql = $"SELECT DISTINCT GroupYear AS YearName,GroupArea AS AreaName  FROM cts_RijianGroup WHERE IsSaved=1 ORDER BY GroupYear DESC";
            List<cts_Area_Year> list = _orgRep.AsSugarClient().Ado.SqlQuery<cts_Area_Year>(sql).ToList();
            var tmpYear = "";
            var finalList = new List<MenuModel>();
            var tmpMenu = new MenuModel();

            foreach (var item in list)
            {
                var tmpChild = new MenuChild();
                tmpChild.YearName = item.YearName;
                tmpChild.AreaName = item.AreaName;
                if (!item.YearName.Equals(tmpYear))
                {
                    tmpYear = item.YearName;
                    tmpMenu = new MenuModel();
                    tmpMenu.Area = new List<MenuChild>();
                    tmpMenu.Year = tmpYear;
                    finalList.Add(tmpMenu);
                }

                tmpMenu.Area.Add(tmpChild);
            }
            return finalList;

        }



        /// <summary>
        /// 查看工作量详情
        /// </summary>     
        /// <returns></returns>
        [HttpPost]
        public dynamic SearchRijianWorkDetail(ReportDto input)
        {
            if (string.IsNullOrEmpty(input.sdate))
            {
                input.sdate = "2015-01-01";
            }
            if (string.IsNullOrEmpty(input.edate))
            {
                input.edate = DateTime.Now.ToString("yyyy-MM-dd");
            }

            var sqlstr = $@"SELECT A.Name,
                                    A.GroupId,
                                    CONVERT(varchar(100),
                                    A.CheckTime,
                                    20) AS CheckTime,
                                    B.GroupName
                            FROM [cts_AssessRijian] A
                            INNER JOIN cts_RijianGroup B
                                ON A.GroupId=B.Gid
                            INNER JOIN 
                                (SELECT DISTINCT OrgId,
                                     sys_Creater,
                                     sys_CreaterName
                                FROM dbo.cts_RijianAssessInfo
                                WHERE DATEDIFF(DAY,'{input.sdate}',sys_CreateDate)>=0
                                        AND DATEDIFF(DAY,sys_CreateDate,'{input.edate}')>=0
                                        AND sys_Creater='{input.empid}') C
                                ON A.Gid=C.OrgId
                            WHERE A.State>0
                                    AND A.sys_IsDelete=0
                                    AND A.Name<>''
                                    AND C.sys_Creater='{input.empid}'";
            return _orgRep.AsSugarClient().SqlQueryable<dynamic>(sqlstr).ToList();
        }
    }
}
